package com.wjpeng.wms.service.impl;

import com.wjpeng.wms.domain.*;
import com.wjpeng.wms.mapper.ProductStockMapper;
import com.wjpeng.wms.mapper.StockIncomeBillItemMapper;
import com.wjpeng.wms.mapper.StockIncomeBillMapper;
import com.wjpeng.wms.query.StockIncomeBillQueryObject;
import com.wjpeng.wms.service.IStockIncomeBillService;
import com.wjpeng.wms.util.PageResult;
import com.wjpeng.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class StockIncomeBillServiceImpl implements IStockIncomeBillService {
    @Autowired
    private StockIncomeBillMapper billMapper;

    @Autowired
    private StockIncomeBillItemMapper itemMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    @Override
    public void saveOrUpdate(StockIncomeBill d) {
        if(d.getId() == null){
            saveBill(d);
        }else{
            updateBill(d);
        }


    }

    //保存订单
    private void saveBill(StockIncomeBill entity){
        //1:设置录入人
        entity.setInputUser(UserContext.getCurrentUser());
        //2:设置录入时间
        entity.setInputTime(new Date());
        //3:设置单据状态
        entity.setStatus(StockIncomeBill.NORMAL);
        //4:定义两个变量,来记录当前单据的总数量和总金额
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        //5:设置明细数据
        for (StockIncomeBillItem item : entity.getItems()) {
            //4.1:计算单据的小计
            BigDecimal amount = item.getCostPrice().multiply(item.getNumber())
                    .setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            //4.2:叠加总数量和总计
            totalNumber = totalNumber.add(item.getNumber());
            totalAmount = totalAmount.add(amount);
        }

        //6:设置单据的总价和总数量
        entity.setTotalNumber(totalNumber);
        entity.setTotalAmount(totalAmount);
        //7:保存单据到数据库中
        billMapper.insert(entity);
        //8:保存明细
        for (StockIncomeBillItem item : entity.getItems()) {
            item.setBillId(entity.getId());
            //保存明细到数据库中
            itemMapper.insert(item);
        }
    }



    //更新单据
    private void updateBill(StockIncomeBill entity) {
        //根据单据的ID查询完整的单据信息
        StockIncomeBill old = billMapper.selectByPrimaryKey(entity.getId());
        //检验当前单据的状态,未审核才能更新
        if(old.getStatus() == StockIncomeBill.NORMAL){
            //核心,重新计算明细小计,单据的总数量和总价格
            //1:删除当前单据所有的明细
            itemMapper.deleteItemByBillId(old.getId());
            //2:定义变量来记录总数和总价
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            //3:计算单据的总价和总数量
            for (StockIncomeBillItem item : entity.getItems()) {
                //3.1:保存明细的总价
                BigDecimal amout = item.getNumber().multiply(item.getCostPrice())
                        .setScale(2, RoundingMode.HALF_UP);
                item.setAmount(amout);
                //3.2叠加总数量和总金额
                totalAmount = totalAmount.add(amout);
                totalNumber = totalNumber.add(item.getNumber());
                //4:保存明细
                item.setBillId(entity.getId());
                itemMapper.insert(item);
            }
            //回填传递的订单数据
            entity.setTotalNumber(totalNumber);
            entity.setTotalAmount(totalAmount);
            //5:更新订单
            billMapper.updateByPrimaryKey(entity);
        }

    }

    @Override
    public void delete(Long id) {
        //根据单据的ID查询完整的单据信息
        StockIncomeBill old = billMapper.selectByPrimaryKey(id);
        //检验当前单据的状态,未审核才能更新
        if(old.getStatus() == StockIncomeBill.NORMAL){
            //删除当前单据的明细,在删除订单
            itemMapper.deleteItemByBillId(id);
            billMapper.deleteByPrimaryKey(id);

        }


    }

    @Override
    public StockIncomeBill get(Long id) {
        return billMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<StockIncomeBill> list() {
        return billMapper.selectAll();
    }

    @Override
    public PageResult result(StockIncomeBillQueryObject qo) {
        Integer count = billMapper.queryCount(qo);
        if(count == 0){
            return new PageResult(Collections.EMPTY_LIST,0,1,0);
        }
        return new PageResult(billMapper.queryLimit(qo),count,qo.getCurrentPage(),qo.getPageSize());
    }

    @Override
    public void audit(Long id) {
        //根据单据的ID查询完整的单据信息
        StockIncomeBill bill = billMapper.selectByPrimaryKey(id);
        //检验当前单据的状态,未审核的才能审核
        if(bill.getStatus() == StockIncomeBill.NORMAL){
            //获取当前入库的仓库
            Depot depot = bill.getDepot();
            //1:迭代当前单据中所有的明细,依次入库
            for (StockIncomeBillItem item : bill.getItems()) {
                //获取当前明细的商品档案
                Product product = item.getProduct();

                //2:查询当前商品所入的仓库中是否拥有该商品的库存
                ProductStock ps = productStockMapper.selectByProductAndDepot(product.getId(), depot.getId());
                if(ps != null){
                    //使用移动加权平均算法
                    BigDecimal number = item.getNumber().add(ps.getStoreNumber());//库存总数量
                    BigDecimal amount = item.getAmount().add(ps.getAmount());//库存总价值
                    BigDecimal price = amount.divide(number, 2, RoundingMode.HALF_UP);//库存平均价值

                    //更新库存信息
                    ps.setStoreNumber(number);
                    ps.setAmount(amount);
                    ps.setPrice(price);
                    //直接创建一个库存对象,存入数据库
                    productStockMapper.updateByPrimaryKey(ps);
                }
            }
            //设置单据的审核人,时间,状态
            bill.setAuditor(UserContext.getCurrentUser());
            bill.setAuditTime(new Date());
            bill.setStatus(StockIncomeBill.AUDIT);
            billMapper.audit(bill);
        }
    }
}
